package com.ant.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.ant.form.User;
import com.ant.service.UserService;
import com.ant.util.SessionUtils;

@Controller
public class LoginController {
	
	@Autowired
    private UserService userService ;
	
	@RequestMapping("/login")
    public String login() {
//        ModelAndView mv = new ModelAndView();
//        mv.setViewName("login");
        return "login";

    }
	
	@RequestMapping(value="/doLogin" , method=RequestMethod.POST)
    public String doLogin(HttpSession session,@RequestParam("username") String username,@RequestParam("password") String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        
//        ModelAndView mv = new ModelAndView;
        if(userService.checkUser(user)){
        	SessionUtils.setUser(session, user);
            
            return "loginSuccess";
            //mv.setViewName("redirect:/index");
        }else{
            return "redirect:/login";
            //mv.setViewName("redirect:/login");
        }
        //return mv;
    }
	
	@RequestMapping(value="/reg")
    public ModelAndView signIn(HttpSession session){
		ModelAndView mv = new ModelAndView();
		mv.addObject("js","reg");
		mv.setViewName("reg");
		return mv;
    }
	
	@RequestMapping(value="/doReg" , method=RequestMethod.POST)
    public @ResponseBody String doSignIn(HttpSession session,@RequestParam("username") String username,@RequestParam("password") String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        
        ModelAndView mv = new ModelAndView();
        if(userService.checkDuplicateUser(user)){
        	return "{\"success\":\"false\"}";
            //mv.setViewName("redirect:/index");
        }else{
        	userService.addUser(user);
        	return "{\"success\":\"true\"}";
        }
        //return mv;
    }
}
